﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace srt2lrc
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
          
        }

        private string ConvertSrtToLrc(string srtContent)
        {
            StringBuilder lrcBuilder = new StringBuilder();
            string[] lines = srtContent.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
            Regex timecodeRegex = new Regex(@"(\d{2}):(\d{2}):(\d{2}),(\d{3})");

            foreach (string line in lines)
            {
                MatchCollection matches = timecodeRegex.Matches(line);
                if (matches.Count > 0)
                {
                    // 只取开始时间
                    var startMatch = matches[0];
                    int hours = int.Parse(startMatch.Groups[1].Value);
                    int minutes = int.Parse(startMatch.Groups[2].Value) + hours * 60; // 转换小时到分钟
                    int seconds = int.Parse(startMatch.Groups[3].Value);
                    int milliseconds = int.Parse(startMatch.Groups[4].Value) / 10; // LRC格式通常使用两位数表示毫秒

                    lrcBuilder.Append($"[{minutes:00}:{seconds:00}.{milliseconds:00}]");
                }
                else if (!string.IsNullOrWhiteSpace(line) && !char.IsDigit(line[0]))
                {
                    // 歌词文本行
                    lrcBuilder.AppendLine(line.Trim());
                }
            }

            return lrcBuilder.ToString();
        }
        
        private void TxtDisplay_OnPreviewDragOver(object sender, DragEventArgs e)
        {
            e.Effects = DragDropEffects.Copy;
            e.Handled = true;
        }

        private void TxtDisplay_OnPreviewDrop(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
                if (files != null && files.Length > 0)
                {
                    string srtContent = File.ReadAllText(files[0]);
                    string lrcContent = ConvertSrtToLrc(srtContent);
                    txtDisplay.Text = lrcContent;
                }
            }
        }
    }
}